package part15exceptionhandle;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @description: 实例化，传入自己的ThreadFactory，设置Thread.UncaughtExceptionHandler处理未检测的异常
 * @author: sali
 * @date: 2024/3/30 09:52.
 * @version: 1.0
 */
public class Test02 {

    public static void main(String[] args) {
        // 创建自定义的线程工厂
        CustomThreadFactory threadFactory = new CustomThreadFactory();

        // 使用自定义线程工厂实例化线程池
        ExecutorService executor = Executors.newFixedThreadPool(2, threadFactory);

        // 提交任务
        for (int i = 0; i < 5; i++) {
            executor.execute(() -> {
                System.out.println("执行任务");
                throw new RuntimeException("任务执行异常");
            });
        }

        // 关闭线程池
        executor.shutdown();
    }
}



class CustomThreadFactory implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
        // 创建新线程
        Thread thread = new Thread(r);

        // 设置未捕获异常处理器
        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                // 在这里处理未捕获的异常
                System.err.println("线程 " + t.getName() + " 抛出未捕获的异常: " + e.getMessage());
                // 这里你可以进行异常处理，比如记录日志或者执行其他操作
            }
        });

        return thread;
    }
}